Page({
  data: {
    totalPoints: 0,
    pointsHistory: [
      {
        id: 1,
        title: '完成团队会议',
        points: 10,
        date: '2024-03-15 10:30',
        type: 'earn'
      },
      {
        id: 2,
        title: '完成健身',
        points: 5,
        date: '2024-03-15 19:30',
        type: 'earn'
      },
      {
        id: 3,
        title: '兑换电影票',
        points: -50,
        date: '2024-03-14 14:20',
        type: 'spend'
      }
    ],
    rewards: [
      {
        id: 1,
        title: '看一部电影',
        points: 50,
        icon: 'movie'
      },
      {
        id: 2,
        title: '买一杯奶茶',
        points: 100,
        icon: 'drink'
      },
      {
        id: 3,
        title: '休息半天',
        points: 200,
        icon: 'rest'
      }
    ],
    penalties: [
      {
        id: 1,
        title: '额外加班1小时',
        points: 30,
        icon: 'work'
      },
      {
        id: 2,
        title: '跑步5公里',
        points: 50,
        icon: 'run'
      }
    ],
    thresholds: {
      reward: 100, // 积分达到100可获得奖励
      penalty: 20  // 积分低于20将受到惩罚
    },
    showSettingsDialog: false,
    showAddRewardDialog: false,
    showAddPenaltyDialog: false,
    rewardForm: {
      id: 0,
      title: '',
      points: 50,
      icon: 'gift'
    },
    penaltyForm: {
      id: 0,
      title: '',
      points: 30,
      icon: 'warning'
    },
    isEditReward: false,
    isEditPenalty: false,
    iconOptions: [
      'gift', 'movie', 'drink', 'food', 'rest', 
      'game', 'music', 'book', 'travel', 'work', 
      'run', 'gym', 'warning', 'star'
    ]
  },
  
  onLoad: function() {
    // 从全局状态获取积分
    const app = getApp();
    if (app.globalData && app.globalData.points !== undefined) {
      this.setData({
        totalPoints: app.globalData.points
      });
    } else {
      this.calculateTotalPoints();
    }
    
    // 检查积分状态
    this.checkPointsStatus();
  },
  
  // 计算总积分
  calculateTotalPoints: function() {
    const total = this.data.pointsHistory.reduce((sum, record) => sum + record.points, 0);
    this.setData({ totalPoints: total });
  },
  
  // 检查积分状态
  checkPointsStatus: function() {
    const { totalPoints, thresholds } = this.data;
    
    if (totalPoints >= thresholds.reward) {
      wx.showModal({
        title: '恭喜！',
        content: `您的积分已达到奖励标准 (${thresholds.reward}分)，可以兑换奖励了！`,
        showCancel: false
      });
    } else if (totalPoints < thresholds.penalty) {
      wx.showModal({
        title: '注意！',
        content: `您的积分低于惩罚标准 (${thresholds.penalty}分)，需要完成一项惩罚任务。`,
        showCancel: false
      });
    }
  },
  
  // 显示设置弹窗
  showSettingsDialog: function() {
    this.setData({
      showSettingsDialog: true
    });
  },
  
  // 关闭设置弹窗
  closeSettingsDialog: function() {
    this.setData({
      showSettingsDialog: false
    });
  },
  
  // 保存设置
  saveSettings: function() {
    this.setData({
      showSettingsDialog: false
    });
    
    wx.showToast({
      title: '设置已保存',
      icon: 'success'
    });
    
    this.checkPointsStatus();
  },
  
  // 奖励阈值变化
  onRewardThresholdChange: function(e) {
    this.setData({
      'thresholds.reward': e.detail.value
    });
  },
  
  // 惩罚阈值变化
  onPenaltyThresholdChange: function(e) {
    this.setData({
      'thresholds.penalty': e.detail.value
    });
  },
  
  // 显示添加奖励弹窗
  showAddRewardDialog: function() {
    this.setData({
      showAddRewardDialog: true,
      isEditReward: false,
      rewardForm: {
        id: Date.now(),
        title: '',
        points: 50,
        icon: 'gift'
      }
    });
  },
  
  // 关闭奖励弹窗
  closeRewardDialog: function() {
    this.setData({
      showAddRewardDialog: false
    });
  },
  
  // 保存奖励
  saveReward: function() {
    const form = this.data.rewardForm;
    
    if (!form.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }
    
    const rewards = [...this.data.rewards];
    
    if (this.data.isEditReward) {
      // 编辑模式
      const index = rewards.findIndex(r => r.id === form.id);
      if (index !== -1) {
        rewards[index] = {...form};
      }
    } else {
      // 新增模式
      rewards.push({...form});
    }
    
    this.setData({
      rewards,
      showAddRewardDialog: false
    });
    
    wx.showToast({
      title: this.data.isEditReward ? '修改成功' : '添加成功',
      icon: 'success'
    });
  },
  
  // 编辑奖励
  editReward: function(e) {
    const id = e.currentTarget.dataset.id;
    const reward = this.data.rewards.find(r => r.id === id);
    
    if (reward) {
      this.setData({
        isEditReward: true,
        showAddRewardDialog: true,
        rewardForm: {...reward}
      });
    }
  },
  
  // 删除奖励
  deleteReward: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个奖励吗？',
      success: res => {
        if (res.confirm) {
          const rewards = this.data.rewards.filter(r => r.id !== id);
          this.setData({ rewards });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },
  
  // 显示添加惩罚弹窗
  showAddPenaltyDialog: function() {
    this.setData({
      showAddPenaltyDialog: true,
      isEditPenalty: false,
      penaltyForm: {
        id: Date.now(),
        title: '',
        points: 30,
        icon: 'warning'
      }
    });
  },
  
  // 关闭惩罚弹窗
  closePenaltyDialog: function() {
    this.setData({
      showAddPenaltyDialog: false
    });
  },
  
  // 保存惩罚
  savePenalty: function() {
    const form = this.data.penaltyForm;
    
    if (!form.title) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }
    
    const penalties = [...this.data.penalties];
    
    if (this.data.isEditPenalty) {
      // 编辑模式
      const index = penalties.findIndex(p => p.id === form.id);
      if (index !== -1) {
        penalties[index] = {...form};
      }
    } else {
      // 新增模式
      penalties.push({...form});
    }
    
    this.setData({
      penalties,
      showAddPenaltyDialog: false
    });
    
    wx.showToast({
      title: this.data.isEditPenalty ? '修改成功' : '添加成功',
      icon: 'success'
    });
  },
  
  // 编辑惩罚
  editPenalty: function(e) {
    const id = e.currentTarget.dataset.id;
    const penalty = this.data.penalties.find(p => p.id === id);
    
    if (penalty) {
      this.setData({
        isEditPenalty: true,
        showAddPenaltyDialog: true,
        penaltyForm: {...penalty}
      });
    }
  },
  
  // 删除惩罚
  deletePenalty: function(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除这个惩罚吗？',
      success: res => {
        if (res.confirm) {
          const penalties = this.data.penalties.filter(p => p.id !== id);
          this.setData({ penalties });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },
  
  // 兑换奖励
  redeemReward: function(e) {
    const id = e.currentTarget.dataset.id;
    const reward = this.data.rewards.find(r => r.id === id);
    
    if (reward) {
      if (this.data.totalPoints < reward.points) {
        wx.showToast({
          title: '积分不足',
          icon: 'none'
        });
        return;
      }
      
      wx.showModal({
        title: '确认兑换',
        content: `确定要兑换"${reward.title}"吗？需要消耗${reward.points}积分。`,
        success: res => {
          if (res.confirm) {
            // 添加兑换记录
            const history = this.data.pointsHistory;
            history.unshift({
              id: Date.now(),
              title: `兑换: ${reward.title}`,
              points: -reward.points,
              date: this.formatDate(new Date()),
              type: 'spend'
            });
            
            this.setData({ pointsHistory: history });
            this.calculateTotalPoints();
            
            // 更新全局积分状态
            const app = getApp();
            app.globalData = app.globalData || {};
            app.globalData.points = this.data.totalPoints;
            
            wx.showToast({
              title: '兑换成功',
              icon: 'success'
            });
          }
        }
      });
    }
  },
  
  // 接受惩罚
  acceptPenalty: function(e) {
    const id = e.currentTarget.dataset.id;
    const penalty = this.data.penalties.find(p => p.id === id);
    
    if (penalty) {
      wx.showModal({
        title: '确认接受',
        content: `确定要接受"${penalty.title}"惩罚吗？完成后可获得${penalty.points}积分。`,
        success: res => {
          if (res.confirm) {
            // 添加惩罚记录
            const history = this.data.pointsHistory;
            history.unshift({
              id: Date.now(),
              title: `惩罚: ${penalty.title}`,
              points: penalty.points,
              date: this.formatDate(new Date()),
              type: 'earn'
            });
            
            this.setData({ pointsHistory: history });
            this.calculateTotalPoints();
            
            // 更新全局积分状态
            const app = getApp();
            app.globalData = app.globalData || {};
            app.globalData.points = this.data.totalPoints;
            
            wx.showToast({
              title: '已接受惩罚',
              icon: 'success'
            });
          }
        }
      });
    }
  },
  
  // 表单输入变化
  onInputChange: function(e) {
    const { field, type } = e.currentTarget.dataset;
    const value = field === 'points' ? parseInt(e.detail.value) : e.detail.value;
    
    if (type === 'reward') {
      this.setData({
        [`rewardForm.${field}`]: value
      });
    } else if (type === 'penalty') {
      this.setData({
        [`penaltyForm.${field}`]: value
      });
    }
  },
  
  // 选择图标
  selectIcon: function(e) {
    const { icon, type } = e.currentTarget.dataset;
    
    if (type === 'reward') {
      this.setData({
        'rewardForm.icon': icon
      });
    } else if (type === 'penalty') {
      this.setData({
        'penaltyForm.icon': icon
      });
    }
  },
  
  // 阻止事件冒泡
  stopPropagation: function() {
    return;
  },
  
  // 格式化日期
  formatDate: function(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
}) 